//
//  MyIndentsViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyIndentsViewController.h"
#import "MyIndentsTableViewCell.h"
#import "PayTypeViewController.h"
#import "MyIndentsDetailViewController.h"
static NSString * cellIndentifier = @"MyIndentsTableViewCell";
@interface MyIndentsViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray * indentsArray;
@end

@implementation MyIndentsViewController

- (void)viewWillAppear:(BOOL)animated{
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _indentsArray = [NSMutableArray array];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}


- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.indentsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }
    
}

#pragma mark === 获取订单列表
- (void)getIndentsList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMyOrderList withHttpType:@"POST" withTag:GS_GS_queryMyOrderList];
}

#pragma mark == sectionHandel
- (void)sectionHandel:(UIButton *)sender{
    NSDictionary * dic = _indentsArray[sender.tag-100];
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
    NSInteger status = [[NSString stringWithFormat:@"%@",dic[@"mordStatus"]]integerValue];
    if (status == 1) {//未支付
        PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
        page.payOrderPrice = [NSString stringWithFormat:@"%@",dic[@"mordPrice"]];
        page.payTypes = @"2";
        page.payOrderName = @"中磐科技";
        page.payId = [NSString stringWithFormat:@"%@",dic[@"mordNo"]];
        //            page.paySuccessBlock = ^(){
        //                [self backBtn];
        //            };
        [[Common getNavigation]pushViewController:page completion:^{
        }];

    }
   }

#pragma mark  ==== tableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 58*VerticalRatio();
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 58), NO)];
    view.backgroundColor = [UIColor whiteColor];
    
    NSDictionary * dic = _indentsArray[section];
    //商家
    UILabel * company = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(15, 12, 200, 15), NO)];
    company.textColor = [UIColor colorWithWhite:0.200 alpha:1.000];
    company.font = [UIFont systemFontOfSize:15*VerticalRatio()];
    company.text = [NSString stringWithFormat:@"%@",dic[@"mstoName"]];
    [view addSubview:company];
    
    //订单号
    UILabel * number = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(15, 34, 300, 15), NO)];
    number.textColor = [UIColor colorWithWhite:0.200 alpha:1.000];
    number.font = [UIFont systemFontOfSize:15*VerticalRatio()];
    number.text = [NSString stringWithFormat:@"订单号:%@",dic[@"mordNo"]];
    [view addSubview:number];
    
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 57, 320, 1), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    [view addSubview:line];
    
    
    //按钮
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = flexibleFrame(CGRectMake(268, 10, 40, 18), NO);
    [button setTitleColor:[UIColor colorWithRed:1.000 green:0.518 blue:0.000 alpha:1.000] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:13*VerticalTexeRatio()];
    button.layer.masksToBounds = YES;
    button.layer.borderWidth = 1;
    button.tag = 100+section;
    button.layer.borderColor = [UIColor colorWithRed:1.000 green:0.518 blue:0.000 alpha:1.000] .CGColor;
    button.layer.cornerRadius = 2*VerticalRatio();
    [button addTarget:self action:@selector(sectionHandel:) forControlEvents:UIControlEventTouchUpInside];
    NSInteger status = [[NSString stringWithFormat:@"%@",dic[@"mordStatus"]]integerValue];
    NSArray * array = @[@"未支付",@"已支付",@"已发货",@"已收货",@"已取消",@"已删除"];
     [button setTitle:array[status-1] forState:UIControlStateNormal];
    [view addSubview:button];
    
    return view;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _indentsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray * array = _indentsArray[section][@"mallOrderDetail"];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 95*VerticalRatio();
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyIndentsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[MyIndentsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    NSDictionary * dic = _indentsArray[indexPath.section][@"mallOrderDetail"][indexPath.row];
    cell.name.text = [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooName"]];
    cell.totalPrice.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"modePrice"] floatValue]];
    NSString * image = [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooImage"]];
    [cell.indentImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
    MyIndentsDetailViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"MyIndentsDetail"];
    page.indentId = _indentsArray[indexPath.section][@"mordId"];
    page.indentStatus = [[NSString stringWithFormat:@"%@",_indentsArray[indexPath.section][@"mordStatus"]]integerValue];
    [[Common getNavigation]pushViewController:page];
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==GS_GS_queryMyOrderList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.indentsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.indentsArray addObject:entity];
                }
                
                [_tableView reloadData];
                
            });
        
        }
        
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
